var express = require('express');
var router = express.Router();
// const {send} = require('express/lib/response')
const db = require("../db/db");
// const promise = require("../db/promise");
const mailCfg = require('./mailCfg');

// 引入缓存模块
const LocalStorage = require('node-localstorage').LocalStorage,
	localStorage = new LocalStorage('./scratch');


/* GET users listing. */
router.get('/', function(req, res, next) {
	res.send('respond with a resource');
});

// 登录接口
router.get('/login', function(req, res, next) {
	// console.log(req.query)
	let password = req.query.password
	let sql =
		`select * from user where user_email="${req.query.email}" and user_pwd="${req.query.password}"`
	db(sql, (err, data) => {
		if(data.length){
		  // console.log(data[0].password);
		  // if(data[0].password == password){
		    res.json({
		      code:1,
		      message:"登录成功",
		      data:data
		    })
		  // }else{
		  //   res.json({
		  //     code:0,
		  //     message:"邮件地址或密码错误",
		  //   })
		  // }
		}else{
		  res.json({
		    code:0,
		    message:"用户不存在"
		  })
		}
			
	})
	
	// res.send("哈哈哈")
	
	
});


// 发送邮件的接口
router.get('/sendEmail', function (req, res, next) {
  //保存验证码和邮箱，时间
  let user = {};
  let email = req.query.email;
  let code = createSixNum();
  // console.log(code);
  let time = new Date().getTime();
  user.initCode = code;
  user.time = time;
  user.email = email;
  user = JSON.stringify(user);
  // 放入缓存中(注意把每个客户的邮箱当作key)
  localStorage.setItem(email,user)

  let sql = `select * from user where user_email= "${req.query.email}"`;
  db(sql, (err, data) => {
    if (data.length) {
      res.send({
        code: 0,
        message: "邮箱已注册"
      })
    } else {
      var mail = {
        // 发件人
        from: '<2643221986@qq.com>',
        // 主题
        subject: '验证码',//邮箱主题
        // 收件人
        to: email,//前台传过来的邮箱
        // 邮件内容，HTML格式
        text: '用' + code + '作为你的验证码'//发送验证码
      };
      mailCfg(mail)
      res.send({
        code: 1,
        msg: "发送成功"
      })
    }
  })
  // 随机产生六位验证码
  function createSixNum() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
      Num += Math.floor(Math.random() * 10);
    }
    return Num;
  }
});
//验证码校验（注册）
router.post("/jiaoyan", (req, res) => {
  let obody = req.body;
  // 获取缓存
  let user = localStorage.getItem(obody.email)
  user = JSON.parse(user);
  // console.log(student);
  const registerTime = new Date().getTime()
  if (registerTime - user.time >= 5 * 1000 * 60) {
    res.send({
      code: -1,
      msg: '验证码已过期'
    })
  }
  if (user.initCode === obody.code) {
      let sql = `INSERT INTO user (user_email,user_pwd) VALUES ("${email}",${password}")`;
      db(sql,(err,data)=>{

          res.send({
            code: 1,
            message: "注册成功",
            data:data
          })
      })
      // 注册成功删除缓存
      localStorage.removeItem(obody.email);
      // console.log("----------------------");
      // console.log(localStorage.getItem(obody.email));
      // console.log("----------------------");

  }
  else {
    res.send({
      code: 0,
      message: "验证码输入错误"
    })

  }

})



//注册接口
router.all('/register', function(req, res, next) {
	let data
	if (Object.keys(req.body).length) {
		data = req.body
	} else {
		data = req.query
	}

	let name = req.body.name;
	let email = req.body.email;
	let password = req.body.password;
	let sql = `INSERT INTO user (user_name,user_email,user_pwd) VALUES ("${name}","${email}","${password}");`
	db(sql, function(err, data) {
		res.json({
			code: 1,
			message: "注册成功",
			data: data
		})

	
	

	})


	
});

module.exports = router;